﻿@model Entity.NumberingRule
@using Microsoft.AspNetCore.Mvc.Rendering
@using Microsoft.Extensions.Primitives
@{
    // 从URL参数或Model中获取目标表单数据（优先URL参数）
    var targetFormText = Context.Request.Query["target_form"].ToString()
        ?? Model?.target_form
        ?? "";
    targetFormText = System.Net.WebUtility.UrlDecode(targetFormText);

    var targetFormValue = Context.Request.Query["target_form_value"].ToString()
        ?? Model?.target_id.ToString()
        ?? "";
    targetFormValue = System.Net.WebUtility.UrlDecode(targetFormValue);

    var numberPrefix = Context.Request.Query["number_prefix"].ToString()
        ?? Model?.number_prefix
        ?? "";
    numberPrefix = System.Net.WebUtility.UrlDecode(numberPrefix);

    var timeRule = Context.Request.Query["time_rule"].ToString()
        ?? Model?.time_rule
        ?? "YYYYMMDD";
    timeRule = System.Net.WebUtility.UrlDecode(timeRule);

    // 初始化默认值（避免空值导致计算异常）
    var defaultSerialNumber = Model?.serial_number > 0 ? Model.serial_number : 3;
    var defaultStep = Model?.step > 0 ? Model.step : 1;

    // 从后端获取当前登录用户
    var currentOperator = ViewData["CurrentOperator"]?.ToString() ?? "未知用户";
}

<!-- 编辑表单：无action，通过JS提交 -->
<form id="editRuleForm" class="needs-validation" novalidate>
    <!-- 隐藏字段：核心数据传递 -->
    <input type="hidden" name="rule_id" value="@Model?.rule_id">
    <input type="hidden" name="target_id" value="@targetFormValue">
    <input type="hidden" name="target_form" value="@targetFormText">
    <input type="hidden" name="time_rule" id="hiddenTimeRule" value="@timeRule">
    <!-- 隐藏字段：当前登录用户 -->
    <input type="hidden" id="currentOperator" value="@currentOperator">

    <!-- 1. 目标表单（只读） -->
    <div class="row mb-3">
        <label for="TargetFormDisplay" class="col-sm-3 col-form-label text-nowrap">目标表单 <span class="text-danger">*</span></label>
        <div class="col-sm-9">
            <input type="text" class="form-control"
                   id="TargetFormDisplay"
                   value="@targetFormText"
                   readonly
                   style="background-color: #f8f9fa;"
                   required>
            <div class="invalid-feedback">目标表单不能为空</div>
        </div>
    </div>

    <!-- 2. 编号前缀（必填） -->
    <div class="row mb-3">
        <label for="edit_number_prefix" class="col-sm-3 col-form-label text-nowrap">编号前缀 <span class="text-danger">*</span></label>
        <div class="col-sm-9">
            <input type="text" class="form-control"
                   id="edit_number_prefix"
                   name="number_prefix"
                   value="@numberPrefix"
                   placeholder="例如：HP"
                   required
                   minlength="1"
                   maxlength="10"
                   oninput="updateRulePreview()">
            <div class="invalid-feedback">请输入1-10位的编号前缀</div>
        </div>
    </div>

    <!-- 3. 时间规则（复选框） -->
    <div class="row mb-3">
        <label class="col-sm-3 col-form-label">时间规则 <span class="text-danger">*</span></label>
        <div class="col-sm-9 d-flex flex-wrap gap-3 align-items-center">
            <div class="form-check">
                <input class="form-check-input time-checkbox" type="checkbox" id="include_year" name="include_year"
                       data-time-code="YYYY" @(timeRule.Contains("YYYY") ? "checked" : "")>
                <label class="form-check-label" for="include_year">年(YYYY)</label>
            </div>
            <div class="form-check">
                <input class="form-check-input time-checkbox" type="checkbox" id="include_month" name="include_month"
                       data-time-code="MM" @(timeRule.Contains("MM") ? "checked" : "")>
                <label class="form-check-label" for="include_month">月(MM)</label>
            </div>
            <div class="form-check">
                <input class="form-check-input time-checkbox" type="checkbox" id="include_day" name="include_day"
                       data-time-code="DD" @(timeRule.Contains("DD") ? "checked" : "")>
                <label class="form-check-label" for="include_day">日(DD)</label>
            </div>
            <div class="form-check">
                <input class="form-check-input time-checkbox" type="checkbox" id="include_hour" name="include_hour"
                       data-time-code="HH" @(timeRule.Contains("HH") ? "checked" : "")>
                <label class="form-check-label" for="include_hour">时(HH)</label>
            </div>
            <div class="form-check">
                <input class="form-check-input time-checkbox" type="checkbox" id="include_minute" name="include_minute"
                       data-time-code="mm" @(timeRule.Contains("mm") ? "checked" : "")>
                <label class="form-check-label" for="include_minute">分(mm)</label>
            </div>
            <div class="form-check">
                <input class="form-check-input time-checkbox" type="checkbox" id="include_second" name="include_second"
                       data-time-code="ss" @(timeRule.Contains("ss") ? "checked" : "")>
                <label class="form-check-label" for="include_second">秒(ss)</label>
            </div>
            <div class="w-100 invalid-feedback d-none" id="time_rule_error">请至少选择一个时间规则</div>
        </div>
    </div>

    <!-- 4. 流水号位数 -->
    <div class="row mb-3">
        <label for="serial_number" class="col-sm-3 col-form-label text-nowrap">流水号位数 <span class="text-danger">*</span></label>
        <div class="col-sm-9">
            <input type="number" class="form-control"
                   id="serial_number"
                   name="serial_number"
                   value="@defaultSerialNumber"
                   min="1" max="10"
                   required>
            <div class="invalid-feedback">请输入1-10位的流水号位数</div>
        </div>
    </div>

    <!-- 5. 步长 -->
    <div class="row mb-3">
        <label for="step" class="col-sm-3 col-form-label text-nowrap">步长 <span class="text-danger">*</span></label>
        <div class="col-sm-9">
            <input type="number" class="form-control"
                   id="step"
                   name="step"
                   value="@defaultStep"
                   min="1"
                   required>
            <div class="invalid-feedback">请输入至少1的步长</div>
        </div>
    </div>

    <!-- 6. 规则预览 -->
    <div class="row mb-3">
        <label for="number_production_rule" class="col-sm-3 col-form-label">规则预览</label>
        <div class="col-sm-9">
            <input type="text" class="form-control"
                   id="number_production_rule"
                   name="number_production_rule"
                   value=""
                   readonly
                   style="background-color: #fff; border-color: #dee2e6;">
        </div>
    </div>

    <!-- 7. 操作按钮 -->
    <div class="row mt-4">
        <div class="col-sm-9 offset-sm-3 d-flex gap-2">
            <button type="button" class="btn btn-primary" onclick="saveRule()">保存</button>
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
        </div>
    </div>
</form>

<script type="text/javascript">
    // 引入SweetAlert2（若页面未全局引入）
    const loadSweetAlert = () => {
        if (window.Swal) return;
        const script = document.createElement('script');
        script.src = 'https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.all.min.js';
        document.head.appendChild(script);
        const style = document.createElement('link');
        style.rel = 'stylesheet';
        style.href = 'https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css';
        document.head.appendChild(style);
    };
    loadSweetAlert();

    // 规则预览更新
    function updateRulePreview() {
        const preview = document.getElementById('number_production_rule');
        if (!preview) return;

        // 1. 获取编号前缀
        const prefixInput = document.getElementById('edit_number_prefix');
        let prefix = prefixInput ? prefixInput.value : '';

        // 2. 生成时间值
        const now = new Date();
        let timeValue = '';
        if (document.getElementById('include_year')?.checked) timeValue += now.getFullYear();
        if (document.getElementById('include_month')?.checked) timeValue += (now.getMonth() + 1).toString().padStart(2, '0');
        if (document.getElementById('include_day')?.checked) timeValue += now.getDate().toString().padStart(2, '0');
        if (document.getElementById('include_hour')?.checked) timeValue += now.getHours().toString().padStart(2, '0');
        if (document.getElementById('include_minute')?.checked) timeValue += now.getMinutes().toString().padStart(2, '0');
        if (document.getElementById('include_second')?.checked) timeValue += now.getSeconds().toString().padStart(2, '0');
        timeValue = timeValue || (now.getFullYear() + (now.getMonth() + 1).toString().padStart(2, '0') + now.getDate().toString().padStart(2, '0'));

        // 3. 流水号配置
        const serialInput = document.getElementById('serial_number');
        const serialLength = serialInput ? Math.max(parseInt(serialInput.value) || 3, 1) : 3;
        const stepInput = document.getElementById('step');
        const step = stepInput ? Math.max(parseInt(stepInput.value) || 1, 1) : 1;
        const serialNumber = step.toString().padStart(serialLength, '0');

        // 4. 拼接预览
        preview.value = prefix + timeValue + serialNumber;
        console.log(`【预览更新】生成新的规则预览：${preview.value}`);
    }

    // 更新隐藏的时间规则字段
    function updateHiddenTimeRule() {
        const hiddenTimeRule = document.getElementById('hiddenTimeRule');
        if (!hiddenTimeRule) return;
        let timeRule = '';
        document.querySelectorAll('.time-checkbox:checked').forEach(checkbox => {
            timeRule += checkbox.dataset.timeCode || '';
        });
        hiddenTimeRule.value = timeRule || 'YYYYMMDD';
        console.log(`【时间规则更新】当前时间规则字符串：${hiddenTimeRule.value}`);
    }

    // 初始化时间规则复选框
    function initializeTimeRules() {
        const timeRuleValue = document.getElementById('hiddenTimeRule').value;
        if (!timeRuleValue) return;

        const checkboxMap = {
            'YYYY': 'include_year',
            'MM': 'include_month',
            'DD': 'include_day',
            'HH': 'include_hour',
            'mm': 'include_minute',
            'ss': 'include_second'
        };

        Object.keys(checkboxMap).forEach(code => {
            if (timeRuleValue.includes(code)) {
                const checkbox = document.getElementById(checkboxMap[code]);
                if (checkbox) {
                    checkbox.checked = true;
                    console.log(`【时间规则初始化】勾选 ${checkbox.id}（匹配 ${code}）`);
                }
            }
        });
    }

    // 绑定交互事件
    function bindEvents() {
        console.log('【事件绑定】开始绑定表单交互事件');

        // 编号前缀
        const prefixInput = document.getElementById('edit_number_prefix');
        if (prefixInput) {
            prefixInput.addEventListener('input', updateRulePreview);
            prefixInput.addEventListener('change', updateRulePreview);
            console.log('【事件绑定】已绑定编号前缀输入事件');
        }

        // 流水号 & 步长
        const serialInput = document.getElementById('serial_number');
        const stepInput = document.getElementById('step');
        if (serialInput) {
            serialInput.addEventListener('input', updateRulePreview);
            serialInput.addEventListener('change', updateRulePreview);
            console.log('【事件绑定】已绑定流水号输入事件');
        }
        if (stepInput) {
            stepInput.addEventListener('input', updateRulePreview);
            stepInput.addEventListener('change', updateRulePreview);
            console.log('【事件绑定】已绑定步长输入事件');
        }

        // 时间规则复选框
        document.querySelectorAll('.time-checkbox').forEach(checkbox => {
            checkbox.addEventListener('change', () => {
                updateHiddenTimeRule();
                updateRulePreview();
            });
        });
        console.log('【事件绑定】已绑定时间规则复选框事件');
    }

    // 保存规则
    function saveRule() {
        const form = document.getElementById('editRuleForm');
        if (!form) {
            console.error('【保存失败】未找到编辑表单（editRuleForm），无法提交');
            return;
        }

        // 验证时间规则
        const checkedTime = document.querySelectorAll('.time-checkbox:checked').length;
        if (checkedTime === 0) {
            document.getElementById('time_rule_error').classList.remove('d-none');
            return;
        }
        document.getElementById('time_rule_error').classList.add('d-none');

        // 验证表单
        if (!form.checkValidity()) {
            form.reportValidity();
            return;
        }

        // 更新隐藏字段
        updateHiddenTimeRule();

        // 提交数据（按钮置灰防止重复提交）
        const saveBtn = document.querySelector('button.btn-primary');
        saveBtn.disabled = true;
        saveBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 保存中...';

        const formData = {
            rule_id: parseInt(document.querySelector('input[name="rule_id"]').value) || 0,
            target_id: parseInt(document.querySelector('input[name="target_id"]').value),
            number_prefix: document.getElementById('edit_number_prefix').value,
            time_rule: document.getElementById('hiddenTimeRule').value,
            serial_number: parseInt(document.getElementById('serial_number').value),
            step: parseInt(document.getElementById('step').value),
            number_production_rule: document.getElementById('number_production_rule').value
        };

        console.log('【保存数据】提交的数据：', formData);

        // 发送请求
        fetch('/NumberingRule/Save', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(formData)
        })
        .then(res => res.json())
        .then(data => {
            if (data.success) {
                // 成功提示
                Swal.fire({
                    title: '保存成功',
                    text: `规则ID：${data.rule_id}`,
                    icon: 'success',
                    confirmButtonText: '确定'
                }).then(() => {
                    // 关闭模态框（如果存在）
                    const modal = bootstrap.Modal.getInstance(document.getElementById('editModal'));
                    if (modal) modal.hide();
                    // 跳转到主页面
                    setTimeout(() => {
                        window.location.href = '/NumberingRule/Index';
                    }, 500);
                });
            } else {
                // 失败提示
                Swal.fire({
                    title: '保存失败',
                    text: data.message || '未知错误',
                    icon: 'error',
                    confirmButtonText: '确定'
                });
                saveBtn.disabled = false;
                saveBtn.innerHTML = '保存';
            }
        })
        .catch(err => {
            // 网络错误提示
            Swal.fire({
                title: '请求错误',
                text: err.message || '网络异常',
                icon: 'error',
                confirmButtonText: '确定'
            });
            saveBtn.disabled = false;
            saveBtn.innerHTML = '保存';
        });
    }

    // 初始化
    function initialize() {
        // 设置默认前缀（延迟执行确保DOM加载）
        setTimeout(() => {
            const prefixInput = document.getElementById('edit_number_prefix');
            if (prefixInput && !prefixInput.value && '@numberPrefix' !== '') {
                prefixInput.value = '@numberPrefix';
            }
        }, 100);

        // 初始化时间规则、绑定事件、生成预览
        initializeTimeRules();
        bindEvents();
        updateHiddenTimeRule();
        setTimeout(updateRulePreview, 200);
    }

    // DOM 加载完成后初始化
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initialize);
    } else {
        initialize();
    }
</script>